<?php

namespace App\Admin\Controllers\cms;

use App\Models\Article;
use App\Models\CodeBatch;
use App\Service\QrcodeService;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class CodeBatchController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '批量生成二维码';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CodeBatch);

        $grid->column('id', __('Id'));
        $grid->column('nums', __('生产数量'));
        $grid->column('download_url', __('下载'))->display(function($status,$column){
            if($this['status'] == 2){
                return "<span class='badge am-btn-default'>生成失败，请重新生产</span>";
            }else{
                return $column->downloadable();
            }
        });
        $grid->column('article.title', __('溯源名称'));
        $grid->column('created_at', __('创建时间'));
        $grid->column('updated_at', __('更新时间'));
        $grid->actions(function ($actions) {
            $actions->disableView();
        });
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableRowSelector();
        //$grid->disableActions();
        $grid->disableColumnSelector();
        $grid->actions(function ($actions) {
            $actions->disableEdit();
            $actions->disableView();
        });
        return $grid;
    }



    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CodeBatch);
        $form->number('nums', __('生产数量'))->rules('required');
        $form->select('article_id', __('溯源名称'))->options(Article::all()->pluck('title','id'))->rules('required');
        $form->saved(function(Form $form){
            $model = $form->model();
            $server = new QrcodeService();
            $data = $server->batchMakeQrcode($model);
            $model->fill($data)->save();
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->footer(function ($footer) {
            $footer->disableReset();
            $footer->disableViewCheck();
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
        });
        return $form;
    }
}
